package com.acheli.registry.network.packet;

import com.acheli.ACHeli;
import com.acheli.registry.network.ACHMessages;
import com.acheli.rideable.entites.ComponentEntity;
import com.acheli.rideable.entites.RideableEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.simple.SimpleChannel;

import java.util.function.Supplier;

public class RideableSpawnS2CPacket {
    // 添加字符串字段
    private final CompoundTag tag;

    // 从字节缓冲区解码
    public RideableSpawnS2CPacket(FriendlyByteBuf buf) {
        this.tag = buf.readNbt();
    }

    public RideableSpawnS2CPacket(int rideableId, String factoryName) {
        tag = new CompoundTag();
        tag.putInt("rideableId", rideableId);
        tag.putString("factoryName", factoryName);
    }

    // 编码到字节缓冲区
    public void toBytes(FriendlyByteBuf buf) {
        buf.writeNbt(tag);
    }

    private boolean handle(Supplier<NetworkEvent.Context> supplier) {
        int rideableId = tag.getInt("rideableId");
        String factoryName = tag.getString("factoryName");
        ACHeli.LOGGER.info("RideableSpawnS2CPacket => rideableId: " + rideableId);
        ACHeli.LOGGER.info("RideableSpawnS2CPacket => factoryName: " + factoryName);
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            LocalPlayer localPlayer = Minecraft.getInstance().player;
            if (localPlayer != null) {
                ClientLevel level = localPlayer.clientLevel;
                if  (level.getEntity(rideableId) instanceof RideableEntity rideable
                ) {
                    rideable.setUp(factoryName);
                }

            }
        });
        return true;
    }

    public static void register(SimpleChannel channel) {
        channel.messageBuilder(RideableSpawnS2CPacket.class, ACHMessages.id(), NetworkDirection.PLAY_TO_CLIENT)
                .decoder(RideableSpawnS2CPacket::new)
                .encoder(RideableSpawnS2CPacket::toBytes)
                .consumerMainThread(RideableSpawnS2CPacket::handle)
                .add();
    }
}